package com.example.api.controller;


import com.example.api.dto.ResStatusCode;
import com.example.api.exception.CustomException;
import com.example.api.util.CaptchaUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;

/**
 * @author :xushuo
 * 22点13分
 */
@RestController
@RequestMapping("/api/captcha")
@Api("验证码生成和验证接口")
public class CaptchaController {
    private static final Logger log = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @GetMapping("/image")
    @ApiOperation("获取验证码图片接口")
    public void getKaptcha(HttpServletRequest request,
                           HttpServletResponse response,
                           @ApiParam("电话号码")
                           @RequestParam(required = true)
                           String phone
                           ) throws IOException {
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control","no-store,no-cache,post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");

        //设置返回得类型为图片
        response.setContentType("image/jpeg");

        //获取随机验证码
        String capText = defaultKaptcha.createText();
        //放到缓存中
        String key = CaptchaUtil.IMG_CAPTCHA_KEY+phone;

        redisTemplate.boundValueOps(key).set(capText, Duration.ofMinutes(10));

        BufferedImage bi = defaultKaptcha.createImage(capText);

        ServletOutputStream outputStream = response.getOutputStream();

        ImageIO.write(bi,"jpg",outputStream);

        try {
            outputStream.flush();
        } finally {
            outputStream.close();
        }

    }


    @GetMapping("/checkCaptcha")
    @ApiOperation("验证图片验证码与手机号接口")
    public ResponseEntity<String> checkCaptcha(
            @ApiParam("图片验证码")
            String code,
            @ApiParam("手机号码")
            String phone){

        //从缓存获取图片验证码
        String key = CaptchaUtil.IMG_CAPTCHA_KEY+phone;
        String cacheCode = redisTemplate.boundValueOps(key).get();

        if(StringUtils.hasText(cacheCode) && cacheCode.equalsIgnoreCase(code)){
            return ResponseEntity.ok("验证成功");
        }else {
           throw new CustomException(phone, ResStatusCode.CAPTCHA_IMAGE_ERROR.getCode(),ResStatusCode.CAPTCHA_IMAGE_ERROR.getMessage());
        }
    }


    @GetMapping("/sms")
    @ApiOperation("发送短信验证码接口")
    public ResponseEntity<String> getSmsCode(
            @ApiParam("手机号码")
            String phone){
        //获取随机验证码
        String capText = defaultKaptcha.createText();
        //放到缓存
        String key = CaptchaUtil.SMS_CAPTCHA_KEY+phone;
        redisTemplate.boundValueOps(key).set(capText,Duration.ofMinutes(10));

        //通过短信网关发送到客户手机
        log.info("{} 已发送短信 {}",phone,capText);

        return ResponseEntity.ok("已发送");

    }



}
